<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css">


  <meta name="keywords" content="Go,">





  <link rel="alternate" href="/atom.xml" title="King blog" type="application/atom+xml">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2">






<meta name="description" content="三、Golang 变量 3.1 变量的介绍 3.1.1 变量的概念  变量相当于内存中一个数据存储空间的表示，你可以把变量看做是一个房间的门牌号，通过门牌号我们可以找到房间，同理，通过变量名可以访问到变量（值）  3.1.2 变量的使用步骤  声明变量（也叫：定义变量） 非变量赋值 使用变量">
<meta name="keywords" content="Go">
<meta property="og:type" content="article">
<meta property="og:title" content="Go语言核心编程">
<meta property="og:url" content="https://zhongxc.cc/58832782.html">
<meta property="og:site_name" content="King blog">
<meta property="og:description" content="三、Golang 变量 3.1 变量的介绍 3.1.1 变量的概念  变量相当于内存中一个数据存储空间的表示，你可以把变量看做是一个房间的门牌号，通过门牌号我们可以找到房间，同理，通过变量名可以访问到变量（值）  3.1.2 变量的使用步骤  声明变量（也叫：定义变量） 非变量赋值 使用变量">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2022-01-12T09:58:07.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Go语言核心编程">
<meta name="twitter:description" content="三、Golang 变量 3.1 变量的介绍 3.1.1 变量的概念  变量相当于内存中一个数据存储空间的表示，你可以把变量看做是一个房间的门牌号，通过门牌号我们可以找到房间，同理，通过变量名可以访问到变量（值）  3.1.2 变量的使用步骤  声明变量（也叫：定义变量） 非变量赋值 使用变量">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.2',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhongxc.cc/58832782.html">





  <title>Go语言核心编程 | King blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">King blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhongxc.cc/58832782.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="King">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/assets/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="King blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Go语言核心编程</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-01-12T17:58:07+08:00">
                2022-01-12
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2022-01-12T17:58:07+08:00">
                2022-01-12
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Go/" itemprop="url" rel="index">
                    <span itemprop="name">Go</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="三-golang-变量">三、Golang 变量</h3>
<h4 id="3-1-变量的介绍">3.1 变量的介绍</h4>
<h5 id="3-1-1-变量的概念">3.1.1 变量的概念</h5>
<blockquote>
<p>变量相当于内存中一个数据存储空间的表示，你可以把变量看做是一个房间的门牌号，通过门牌号我们可以找到房间，同理，通过变量名可以访问到变量（值）</p>
</blockquote>
<h5 id="3-1-2-变量的使用步骤">3.1.2 变量的使用步骤</h5>
<ol>
<li>声明变量（也叫：定义变量）</li>
<li>非变量赋值</li>
<li>使用变量</li>
</ol>
<a id="more"></a>
<h4 id="3-2-定义变量">3.2 定义变量</h4>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 定义/声明 变量</span></span><br><span class="line">    <span class="keyword">var</span> i <span class="keyword">int</span></span><br><span class="line">    <span class="comment">// 给i变量赋值</span></span><br><span class="line">    i = <span class="number">10</span></span><br><span class="line">    <span class="comment">// 使用变量</span></span><br><span class="line">    fmt.Println(<span class="string">"i="</span>, i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="3-3-变量使用注意事项">3.3 变量使用注意事项</h4>
<h5 id="golang变量使用的多种方式">Golang变量使用的多种方式</h5>
<ol>
<li>指定变量类型，声明后若不赋值，使用默认值</li>
</ol>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// golang的变量使用方式1</span></span><br><span class="line">    <span class="comment">// 第一种，指定变量类型，声明后若不赋值，使用默认值</span></span><br><span class="line">    <span class="keyword">var</span> i <span class="keyword">int</span></span><br><span class="line">    fmt.Println(<span class="string">"i="</span>, i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>根据值自行判定变量类型（类型推导）</li>
</ol>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> num = <span class="number">10.10</span></span><br><span class="line">    fmt.Println(<span class="string">"num="</span>, num)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>省略var，注意 := 左侧的变量不应该是已经声明过的，否则会导致编译报错</li>
</ol>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 下面的方式等价 var name string = "tom"</span></span><br><span class="line">    <span class="comment">// ：= 的 : 不能省略，否则错误</span></span><br><span class="line">    name := <span class="string">"tom"</span></span><br><span class="line">    fmt.Println(<span class="string">"name="</span>, name)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>多变量声明</li>
</ol>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 一次性声明多个变量(方式1)</span></span><br><span class="line">    <span class="keyword">var</span> n1, n2, n3 <span class="keyword">int</span></span><br><span class="line">    fmt.Println(<span class="string">"n1="</span>, n1, <span class="string">"n2="</span>, n2, <span class="string">"n3="</span>, n3)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 一次性声明多个变量(方式2)</span></span><br><span class="line">    <span class="keyword">var</span> n4, name, n6 = <span class="number">100</span>, <span class="string">"tom"</span>, <span class="number">888</span></span><br><span class="line">    fmt.Println(<span class="string">"n4="</span>, n4, <span class="string">"name="</span>, name, <span class="string">"n6="</span>, n6)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 一次性声明多个变量(方式3)，同样可以使用类型推断</span></span><br><span class="line">    n7, name, n8 := <span class="number">100</span>, <span class="string">"tom~"</span>, <span class="number">888</span></span><br><span class="line">    fmt.Println(<span class="string">"n7="</span>, n7, <span class="string">"name="</span>, name, <span class="string">"n8="</span>, n8)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 一次性声明多个全局变量【在go中函数外部定义变量就是全局变量】</span></span><br><span class="line"><span class="comment">// 定义全局变量</span></span><br><span class="line"><span class="keyword">var</span> nn1 = <span class="number">100</span></span><br><span class="line"><span class="keyword">var</span> nn2 = <span class="number">200</span></span><br><span class="line"><span class="keyword">var</span> nname = <span class="string">"jack"</span></span><br><span class="line"><span class="comment">// 上面的声明方式，也可以改成一次性声明</span></span><br><span class="line"><span class="keyword">var</span> (</span><br><span class="line">    nn3 = <span class="number">300</span></span><br><span class="line">    nn4 = <span class="number">900</span></span><br><span class="line">    nname2 = <span class="string">"mary"</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>该区域的数据值可以在同一类型范围内不断变化</li>
</ol>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 该区域的数据值可以在同一类型范围内不断变化</span></span><br><span class="line">    <span class="keyword">var</span> i <span class="keyword">int</span> = <span class="number">200</span></span><br><span class="line">    i = <span class="number">30</span></span><br><span class="line">    fmt.Println(<span class="string">"i="</span>, i)</span><br><span class="line">    i = <span class="number">500</span></span><br><span class="line">    fmt.Println(<span class="string">"i="</span>, i)</span><br><span class="line">    i = <span class="number">2.5</span> <span class="comment">// truncated to integer，原因是不能改变数据的类型</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>Golang的变量如果没有赋初值，编译器会使用默认值，比如int默认值0，string默认值为空串，小数默认为0</li>
</ol>
<h4 id="3-4-变量的声明-初始化和赋值">3.4 变量的声明，初始化和赋值</h4>
<p><strong>声明变量</strong>
基本语法
var 变量名 数据类型
var a int 这就是声明了一个变量，变量名是 a
var num1 float 这也声明了一个变量，表示一个单精度类型的小数，变量名是num1</p>
<p><strong>初始化变量</strong>
在声明变量的时候，就给赋值
var a int = 45 这就是初始化变量 a
使用细节，如果声明时就直接赋值，可忽略数据类型
var b = 400</p>
<p><strong>给变量赋值</strong>
比如先声明了变量
var num int 默认值 0
然后，再给值
num = 800 这就是给变量赋值</p>
<h4 id="3-5-数据类型的基本介绍">3.5 数据类型的基本介绍</h4>
<p>每一种数据都定义了明确的数据类型，在内存中分配了不同大小的内存空间</p>
<p><strong>基本数据类型</strong></p>
<p>​	1. 数值型</p>
<p>​		1.1 整数类型</p>
<p>​		int、int8、int16、int32、int64</p>
<p>​		uint、uint8、uint16、uint32、uint64</p>
<p>​		1.2 浮点类型</p>
<p>​		float32、float64</p>
<p>​	2. 字符型（没有专门的字符型，使用byte来保存单个字母字符）</p>
<p>​	3. 布尔型（bool）</p>
<p>​	4. 字符串（string）官方将string归属到基本数据类型</p>
<p><strong>派生/复杂数据类型</strong></p>
<ol>
<li>指针</li>
<li>数组</li>
<li>结构体（struct）</li>
<li>管道（channel）</li>
<li>函数（也是一种类型）</li>
<li>切片（slice）</li>
<li>接口（interface）</li>
<li>map</li>
</ol>
<h4 id="3-6-整数类型">3.6 整数类型</h4>
<h5 id="3-6-1-基本介绍">3.6.1 基本介绍</h5>
<p>简单的说，就是用于存放整数值的，比如1，-1,2345</p>
<h5 id="3-6-2-整数类型">3.6.2 整数类型</h5>
<table>
<thead>
<tr>
<th>类型</th>
<th>有无符号</th>
<th>占用存储空间</th>
<th>表数范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>int8</td>
<td>有</td>
<td>1子节</td>
<td>-128 ~ 127</td>
<td></td>
</tr>
<tr>
<td>int16</td>
<td>有</td>
<td>2子节</td>
<td>-2^15 ~ 2^15 -1</td>
<td></td>
</tr>
<tr>
<td>int32</td>
<td>有</td>
<td>4子节</td>
<td>-2^31 ~ 2^31 -1</td>
<td></td>
</tr>
<tr>
<td>int64</td>
<td>有</td>
<td>8子节</td>
<td>-2^63 ~ 2^63 -1</td>
<td></td>
</tr>
</tbody>
</table>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 整数类型的使用</span></span><br><span class="line">	<span class="keyword">var</span> i <span class="keyword">int</span> = <span class="number">1</span></span><br><span class="line">	fmt.Println(<span class="string">"i="</span>, i)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 测试一下int8的范围</span></span><br><span class="line">	<span class="comment">// 其他的 int16, int32, int64...类推</span></span><br><span class="line">	<span class="keyword">var</span> j <span class="keyword">int8</span> = <span class="number">128</span></span><br><span class="line">	fmt.Println(<span class="string">"j="</span>, j)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>int的无符号的类型</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>有无符号</th>
<th>占用存储空间</th>
<th>表数范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>uint8</td>
<td>无</td>
<td>1子节</td>
<td>0 ~ 255</td>
<td></td>
</tr>
<tr>
<td>uint16</td>
<td>无</td>
<td>2子节</td>
<td>0 ~ 2^16 -1</td>
<td></td>
</tr>
<tr>
<td>uint32</td>
<td>无</td>
<td>4子节</td>
<td>0 ~ 2^32 -1</td>
<td></td>
</tr>
<tr>
<td>uint64</td>
<td>无</td>
<td>8子节</td>
<td>0 ~ 2^64 -1</td>
<td></td>
</tr>
</tbody>
</table>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// uint8的范围(0-255), 其它的 uint16, uint32, uint64类推即可</span></span><br><span class="line">	<span class="keyword">var</span> k <span class="keyword">uint8</span> = <span class="number">255</span></span><br><span class="line">	fmt.Println(<span class="string">"k="</span>, k)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>int的其他类型说明</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>有无符号</th>
<th>占用存储空间</th>
<th>表数范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>int</td>
<td>有</td>
<td>32位系统4个子节<br>64位系统8个字节</td>
<td>-2^31 ~ 2^31 -1<br>-2^63 ~ 2^63 -1</td>
<td></td>
</tr>
<tr>
<td>uint</td>
<td>无</td>
<td>32位系统4个字节<br>64位系统8个字节</td>
<td>0 ~ 2^32 -1<br>0 ~ 2^64 -1</td>
<td></td>
</tr>
<tr>
<td>rune</td>
<td>有</td>
<td>与int32一样</td>
<td>-2^31 ~ 2^31 -1</td>
<td>等价int32，表示一个Unicode码</td>
</tr>
<tr>
<td>byte</td>
<td>无</td>
<td>与uint8等价</td>
<td>0 ~ 255</td>
<td>当腰存储字符时选用byte</td>
</tr>
</tbody>
</table>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// int, uint, byte的使用</span></span><br><span class="line">	<span class="keyword">var</span> a <span class="keyword">int</span> = <span class="number">8900</span></span><br><span class="line">	fmt.Println(<span class="string">"a="</span>, a)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">var</span> b <span class="keyword">uint</span> = <span class="number">1</span></span><br><span class="line">	<span class="keyword">var</span> c <span class="keyword">byte</span> = <span class="number">255</span></span><br><span class="line">	fmt.Println(<span class="string">"b="</span>, b, <span class="string">"c="</span>, c)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="3-6-3-整型的使用细节">3.6.3 整型的使用细节</h5>
<ol>
<li>
<p>Golang各整数类型分，有符号和无符号，int、uint的大小和系统有关</p>
</li>
<li>
<p>Golang的整型默认声明为int型</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 整型的使用细节</span></span><br><span class="line">	<span class="keyword">var</span> n1 = <span class="number">100</span> <span class="comment">// ? n1 是什么类型</span></span><br><span class="line">	<span class="comment">// 查看某个变量的数据类型</span></span><br><span class="line">	<span class="comment">// fmt.Printf 可以用于做格式化输出</span></span><br><span class="line">	fmt.Printf(<span class="string">"n1 的类型 %T \n"</span>, n1)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li>
<p>如何在程序查看某个变量的子节大小和数据类型（使用较多）</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> n2 <span class="keyword">int64</span> = <span class="number">10</span></span><br><span class="line">	<span class="comment">// unsafe.Sizeof(n1)是unsafe包的一个函数，可以返回n1变量占用的字节数</span></span><br><span class="line">	fmt.Printf(<span class="string">"n2 的类型 %T, n2占用的字节数是 %d"</span>, n2, unsafe.Sizeof(n2))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li>
<p>Golang程序中，整型变量在使用时，遵守保小不保大的原则，即：在保证程序正确运行下，尽量使用占用空间小的数据类型</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> age <span class="keyword">byte</span> = <span class="number">90</span></span><br><span class="line">	fmt.Printf(<span class="string">"age 的类型 %T, age占用的字节数是 %d"</span>, age, unsafe.Sizeof(age))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li>
<p>bit：计算机中的最小存储单位，byte计算机中基本存储单元，1byte = 8bit</p>
</li>
</ol>
<h4 id="3-7-小数类型-浮点型">3.7 小数类型/浮点型</h4>
<h5 id="3-7-1-基本介绍">3.7.1 基本介绍</h5>
<p>小数类型就是用于存放小数的，比如1.2、0.23、-1.922</p>
<h5 id="3-7-2-小数类型使用">3.7.2 小数类型使用</h5>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> price <span class="keyword">float32</span> = <span class="number">89.12</span></span><br><span class="line">	fmt.Println(<span class="string">"price="</span>, price)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="3-7-3-小数类型分类">3.7.3 小数类型分类</h5>
<table>
<thead>
<tr>
<th>类型</th>
<th>占用存储空间</th>
<th>表数范围</th>
</tr>
</thead>
<tbody>
<tr>
<td>单精度float32</td>
<td>4字节</td>
<td>-3.403E38 ~ 3.403E38</td>
</tr>
<tr>
<td>双精度float64</td>
<td>8字节</td>
<td>-1.798E308 ~ 1.798E308</td>
</tr>
</tbody>
</table>
<p>对表格的说明</p>
<ol>
<li>
<p>关于浮点数在机器中存放形式的简单说明，浮点数=符号位 + 指数位</p>
<p>说明：浮点数都是有符号的</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> price <span class="keyword">float32</span> = <span class="number">89.12</span></span><br><span class="line">	fmt.Println(<span class="string">"price="</span>, price)</span><br><span class="line">	<span class="keyword">var</span> num1 <span class="keyword">float32</span> = <span class="number">-0.00089</span></span><br><span class="line">	<span class="keyword">var</span> num2 <span class="keyword">float64</span> = <span class="number">-7809656.09</span></span><br><span class="line">	fmt.Println(<span class="string">"num1="</span>, num1, <span class="string">"num2="</span>, num2)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">price= <span class="number">89.12</span></span><br><span class="line">num1= <span class="number">-0.00089</span> num2= <span class="number">-7.80965609e+06</span></span><br></pre></td></tr></table></figure>
</li>
<li>
<p>尾数部分可能丢失，造成精度损失</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 尾数部分可能丢失，造成精度损失，-123.0000901</span></span><br><span class="line">	<span class="keyword">var</span> num3 <span class="keyword">float32</span> = <span class="number">-123.0000901</span></span><br><span class="line">	<span class="keyword">var</span> num4 <span class="keyword">float64</span> = <span class="number">-123.0000901</span></span><br><span class="line">	fmt.Println(<span class="string">"num3="</span>, num3, <span class="string">"num4="</span>, num4)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">num3= <span class="number">-123.00009</span> num4= <span class="number">-123.0000901</span></span><br></pre></td></tr></table></figure>
<p>说明，float64的精度比float32要准确，如果我们要保存一个精度高的数，则应该选用float64</p>
</li>
<li>
<p>浮点型的存储分为三部分，符号位+指数位+尾数位，在存储过程中，精度会有丢失</p>
</li>
</ol>
<h5 id="3-7-4-浮点型使用细节">3.7.4 浮点型使用细节</h5>
<ol>
<li>
<p>Golang浮点类型有固定的范围和字段长度，不受具体OS（操作系统）的影响</p>
</li>
<li>
<p>Golang的浮点型默认声明为float64类型</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> num = <span class="number">1.1</span></span><br><span class="line">	fmt.Printf(<span class="string">"num的数据类型是 %T \n"</span>, num)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">num的数据类型是 <span class="keyword">float64</span></span><br></pre></td></tr></table></figure>
</li>
<li>
<p>浮点型常量有两种表示形式</p>
<p>十进制数形式，如：5.12、.512（必须有小数点）</p>
<p>科学计数法形式，如：5.1234e2 = 5.12 * 10的2次方	5.12E-2 = 5.12/10的2次方</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 十进制数形式，5.12，.123</span></span><br><span class="line">	num1 := <span class="number">5.12</span></span><br><span class="line">	num2 := <span class="number">.123</span> <span class="comment">// =&gt; 0.123</span></span><br><span class="line">	fmt.Println(<span class="string">"num1="</span>, num1, <span class="string">"num2="</span>, num2)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 科学计数法形式</span></span><br><span class="line">	num3 := <span class="number">5.1234e2</span>	<span class="comment">// 5.1234 * 10的2次方</span></span><br><span class="line">	num4 := <span class="number">5.1234E2</span> 	<span class="comment">// 5.1234 * 10的2次方</span></span><br><span class="line">	num5 := <span class="number">5.1234E-2</span>	<span class="comment">// 5.1234 / 10的2次方</span></span><br><span class="line">	fmt.Println(<span class="string">"num3="</span>, num3, <span class="string">"num4="</span>, num4, <span class="string">"num5="</span>, num5)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">num1= <span class="number">5.12</span> num2= <span class="number">0.123</span></span><br><span class="line">num3= <span class="number">512.34</span> num4= <span class="number">512.34</span> num5= <span class="number">0.051234</span></span><br></pre></td></tr></table></figure>
</li>
<li>
<p>通常情况下，应该使用float64，因为它比float32更精确，开发中 推荐使用float64</p>
</li>
</ol>
<h4 id="3-8-字符类型">3.8 字符类型</h4>
<h5 id="3-8-1-基本介绍">3.8.1 基本介绍</h5>
<p>​		Golang中没有专门的字符类型，如果要存储单个字符（字母），一般使用byte来保存</p>
<p>​		字符串就是一串固定长度的字符连接起来的字符序列，Go的字符串是由单个子节连接起来的，也就是说对于传统的字符串是由字符组成的，而Go的字符串不同，它是由字节组成的。</p>
<h5 id="3-8-2-基本使用">3.8.2 基本使用</h5>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> c1 <span class="keyword">byte</span> = <span class="string">'a'</span></span><br><span class="line">	<span class="keyword">var</span> c2 <span class="keyword">byte</span> = <span class="string">'0'</span> <span class="comment">// 字符的0</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// 当直接输出byte值，就是输出了对应的字符的码值</span></span><br><span class="line">	fmt.Println(<span class="string">"c1="</span>, c1)</span><br><span class="line">	fmt.Println(<span class="string">"c2="</span>, c2)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 如果希望输出对应的字符，需要使用格式化输出</span></span><br><span class="line">	fmt.Printf(<span class="string">"c1=%c c2=%c"</span>, c1, c2)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// var c3 byte = '北' // 21271 overflows byte</span></span><br><span class="line">	<span class="keyword">var</span> c3 <span class="keyword">int</span> = <span class="string">'北'</span></span><br><span class="line">	fmt.Printf(<span class="string">"c3=%c c3对应码值=%d"</span>, c3, c3)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">c1= <span class="number">97</span></span><br><span class="line">c2= <span class="number">48</span></span><br><span class="line">c1=a c2=<span class="number">0</span>c3=北 c3对应码值=<span class="number">21271</span></span><br></pre></td></tr></table></figure>
<p>上面代码说明</p>
<ol>
<li>如果我们保存的字符在ASCII表的，比如 [0-1, a-z, A-Z...] 直接可以保持到byte</li>
<li>如果我们保存的字符对应的码值大于255，这时我们可以考虑使用int类型保存</li>
<li>如果我们需要按照字符的方式输出，这时需要格式化输出，即fmt.Printf(&quot;%c&quot;, c1)</li>
</ol>
<h5 id="3-8-3-字符类型使用细节">3.8.3 字符类型使用细节</h5>
<ol>
<li>
<p>字符常量是用单引号（''）括起来的单个字符，例如var c1 byte = 'a' var c2 byte = '中' var c3 byte = '9'</p>
</li>
<li>
<p>Go中允许使用转义字符 '\' 来 将其后的字符转变为特殊字符型常量，例如 var c3 char = '\n' \n表示换行符</p>
</li>
<li>
<p>Go语言的字符使用UTF-8编码，如果想查看字符对应的utf8码值，<a href="http://www.mytju.com/classcode/tools/encode_utf8.asp" target="_blank" rel="noopener">http://www.mytju.com/classcode/tools/encode_utf8.asp</a></p>
</li>
<li>
<p>在Go中，字符的本质是一个整数，直接输出时，是该字符对应的UTF-8编码的码值</p>
</li>
<li>
<p>可以直接给某个变量赋一个数字，然后按格式化输出时%c，会输出对应的Unicode字符</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> c1 <span class="keyword">int</span> = <span class="number">26149</span></span><br><span class="line">	fmt.Printf(<span class="string">"c1=%c \n"</span>, c1)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">c1=春</span><br></pre></td></tr></table></figure>
</li>
<li>
<p><strong>字符类型是可以运算的</strong>，相当于一个整数，因为它都对应有Unicode码</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> n1 = <span class="number">10</span> + <span class="string">'a'</span></span><br><span class="line">	fmt.Println(<span class="string">"n1="</span>, n1)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">n1= <span class="number">107</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="3-8-4-字符类型本质探讨">3.8.4 字符类型本质探讨</h5>
<ol>
<li>
<p>字符型 存储到 计算机中，需要将字符对应的码值（整数）找出来</p>
<p>存储：字符 --&gt; 对应的码值  --&gt;  二进制  -&gt;  存储</p>
<p>读取：二进制  --&gt; 码值  --&gt;  字符  --&gt;  读取</p>
</li>
<li>
<p>字符和码值的对应关系是通过字符编码表决定的</p>
</li>
<li>
<p>Go语言的编码都统一成了UTF-8</p>
</li>
</ol>
<h4 id="3-9-布尔类型">3.9 布尔类型</h4>
<h5 id="3-9-1-基本介绍">3.9.1 基本介绍</h5>
<ol>
<li>布尔类型也叫bool类型，bool类型数据只允许读取值 true 和 false</li>
<li>bool类型占一个字节</li>
<li>bool类型适用于逻辑运算，一般用于程序流程控制</li>
</ol>
<h5 id="3-9-2-基本使用">3.9.2 基本使用</h5>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> b = <span class="literal">false</span></span><br><span class="line">	fmt.Println(<span class="string">"b="</span>, b)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// bool类型占用存储空间一个字节</span></span><br><span class="line">	fmt.Println(<span class="string">"b 的占用空间"</span>, unsafe.Sizeof(b))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">b= <span class="literal">false</span></span><br><span class="line">b 的占用空间 <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="3-10-string类型">3.10 string类型</h4>
<p>​		字符串就是一串固定长度的字符连接起来的字符序列，Go字符串是单个字节连接起来的，Go语言的字符串的字节使用UTF-8编码标识Unicode文本</p>
<h5 id="3-10-1-基本使用">3.10.1 基本使用</h5>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> str <span class="keyword">string</span> = <span class="string">"北京长城 110 hello word"</span></span><br><span class="line">	fmt.Println(str)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">北京长城 <span class="number">110</span> hello word</span><br></pre></td></tr></table></figure>
<h5 id="3-10-2-string使用注意事项和细节">3.10.2 string使用注意事项和细节</h5>
<ol>
<li>
<p>Go语言的字符串的字节使用UTF-8编码标识Unicode文本，Golang统一使用UTF-8编码</p>
</li>
<li>
<p>字符串一旦赋值了，就不能修改了，在Go中字符串是不可变的</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> str <span class="keyword">string</span> = <span class="string">"hello"</span></span><br><span class="line">	str[<span class="number">0</span>] = <span class="string">'b'</span></span><br><span class="line">	fmt.Println(<span class="string">"str="</span>, str)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line"># command-line-arguments</span><br><span class="line">.\hello.<span class="keyword">go</span>:<span class="number">198</span>:<span class="number">9</span>: cannot assign to str[<span class="number">0</span>] (strings are immutable)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="3-11-基本数据类型的默认值">3.11 基本数据类型的默认值</h4>
<h5 id="3-11-1-基本介绍">3.11.1 基本介绍</h5>
<p>​		Go中，数据类型都有一个默认值，当程序员没有赋值时，就会保留默认值，默认值又叫零值</p>
<h5 id="3-11-2-基本数据类型默认值如下">3.11.2 基本数据类型默认值如下</h5>
<table>
<thead>
<tr>
<th>数据类型</th>
<th>默认值</th>
</tr>
</thead>
<tbody>
<tr>
<td>整型</td>
<td>0</td>
</tr>
<tr>
<td>浮点型</td>
<td>0</td>
</tr>
<tr>
<td>字符串</td>
<td>&quot;&quot;</td>
</tr>
<tr>
<td>布尔类型</td>
<td>false</td>
</tr>
</tbody>
</table>
<h4 id="3-12-基本数据类型的相互转换">3.12 基本数据类型的相互转换</h4>
<h5 id="3-12-1-基本介绍">3.12.1 基本介绍</h5>
<p>​		Golang和Java/c不同，Go在不同类型的变量之间赋值时<strong>需要显示转换</strong>，也就是说Golang中数据类型<strong>不能自动转换</strong>。</p>
<h5 id="3-12-2-基本语法">3.12.2 基本语法</h5>
<p>表达式 <strong>T(v)</strong> 将 <strong>v</strong> 转换为类型 <strong>T</strong></p>
<p><strong>T</strong>：就是数据类型，比如int32、int64、float32等等</p>
<p><strong>v</strong>：就是需要转换的变量</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> i <span class="keyword">int32</span> = <span class="number">100</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">var</span> n1 <span class="keyword">float32</span> = <span class="keyword">float32</span>(i)</span><br><span class="line">	<span class="keyword">var</span> n2 <span class="keyword">int8</span> = <span class="keyword">int8</span>(i)</span><br><span class="line">	<span class="keyword">var</span> n3 <span class="keyword">int64</span> = <span class="keyword">int64</span>(i)</span><br><span class="line"></span><br><span class="line">	fmt.Printf(<span class="string">"i=%v n1=%v n2=%v n3=%v"</span>, i, n1, n2, n3)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">i=<span class="number">100</span> n1=<span class="number">100</span> n2=<span class="number">100</span> n3=<span class="number">100</span></span><br></pre></td></tr></table></figure>
<h5 id="3-12-3-基本数据类型相互转换的注意事项">3.12.3 基本数据类型相互转换的注意事项</h5>
<ol>
<li>
<p>Go中，数据类型的转换可以从 表示范围小 到 表示范围大，也可以从表示范围大 到 表示范围小</p>
</li>
<li>
<p>被转换的是变量的数据（即值），变量本身的类型并没有发生变化</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> i <span class="keyword">int32</span> = <span class="number">100</span></span><br><span class="line">	<span class="keyword">var</span> n1 <span class="keyword">float32</span> = <span class="keyword">float32</span>(i)</span><br><span class="line">	<span class="keyword">var</span> n2 <span class="keyword">int8</span> = <span class="keyword">int8</span>(i)</span><br><span class="line">	<span class="keyword">var</span> n3 <span class="keyword">int64</span> = <span class="keyword">int64</span>(i) <span class="comment">// 低精度转高精度</span></span><br><span class="line"></span><br><span class="line">	fmt.Println(<span class="string">"i=%v n1=%v n2=%v n3=%v \n"</span>, i, n1, n2, n3)</span><br><span class="line"></span><br><span class="line">	fmt.Printf(<span class="string">"i type is %T "</span>, i)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">i=%v n1=%v n2=%v n3=%v</span><br><span class="line"> <span class="number">100</span> <span class="number">100</span> <span class="number">100</span> <span class="number">100</span></span><br><span class="line">i <span class="keyword">type</span> is <span class="keyword">int32</span></span><br></pre></td></tr></table></figure>
</li>
<li>
<p>在转换中，比如将int64转成int8【-128 ~ 127】，编译时不会报错，只是转换的结果是按溢出处理，和希望的结果不一样，因此在转换时，需要考虑范围。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> num1 <span class="keyword">int64</span> = <span class="number">999999</span></span><br><span class="line">	<span class="keyword">var</span> num2 <span class="keyword">int8</span> = <span class="keyword">int8</span>(num1)</span><br><span class="line">	fmt.Println(<span class="string">"num2="</span>, num2)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">num2= <span class="number">63</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="3-13-基本数据类型和string的转换">3.13 基本数据类型和string的转换</h4>
<h5 id="3-13-1-基本介绍">3.13.1 基本介绍</h5>
<p>​		在程序开发过程中，经常将基本数据类型转成string，或者将string转成基本数据类型</p>
<h5 id="3-13-2-基本类型转string">3.13.2 基本类型转string</h5>
<ol>
<li>
<p>fmt.Sprintf(&quot;%参数&quot;, 表达式)</p>
<p>函数介绍</p>
<p>func Sprintf</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Sprintf</span><span class="params">(format <span class="keyword">string</span>, a ...<span class="keyword">interface</span>&#123;&#125;)</span> <span class="title">string</span></span></span><br></pre></td></tr></table></figure>
<p>Sprintf根据format参数生成格式化的字符串并返回该字符串</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 基本类型转换成string</span></span><br><span class="line">	<span class="keyword">var</span> num1 <span class="keyword">int</span> = <span class="number">99</span></span><br><span class="line">	<span class="keyword">var</span> num2 <span class="keyword">float64</span> = <span class="number">23.456</span></span><br><span class="line">	<span class="keyword">var</span> b <span class="keyword">bool</span> = <span class="literal">true</span></span><br><span class="line">	<span class="keyword">var</span> myChar <span class="keyword">byte</span> = <span class="string">'h'</span></span><br><span class="line">	<span class="keyword">var</span> str <span class="keyword">string</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// 使用fmt.Sprintf方法</span></span><br><span class="line">	str = fmt.Sprintf(<span class="string">"%d"</span>, num1)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line"></span><br><span class="line">	str = fmt.Sprintf(<span class="string">"%f"</span>, num2)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line"></span><br><span class="line">	str = fmt.Sprintf(<span class="string">"%t"</span>, b)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line"></span><br><span class="line">	str = fmt.Sprintf(<span class="string">"%c"</span>, myChar)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"99"</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"23.456000"</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"true"</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"h"</span></span><br></pre></td></tr></table></figure>
</li>
<li>
<p>使用strconv包的函数
func FormatBool(b bool) string
func FormatInt(i int64, base int) string
func FormatUint(i uint64, base int) string
func FormatFloat(f float64, fmt byte, prec, bitSize int) string</p>
</li>
</ol>
  <figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用strconv函数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> num1 <span class="keyword">int</span> = <span class="number">99</span></span><br><span class="line">	<span class="keyword">var</span> num2 <span class="keyword">float64</span> = <span class="number">23.456</span></span><br><span class="line">	<span class="keyword">var</span> b2 <span class="keyword">bool</span> = <span class="literal">true</span></span><br><span class="line">	<span class="keyword">var</span> str <span class="keyword">string</span></span><br><span class="line"></span><br><span class="line">	str = strconv.FormatInt(<span class="keyword">int64</span>(num1), <span class="number">10</span>)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 'f'：格式，10：表示小数位保留10位，64：表示这个小数是float64</span></span><br><span class="line">	str = strconv.FormatFloat(num2, <span class="string">'f'</span>, <span class="number">10</span>, <span class="number">64</span>)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line"></span><br><span class="line">	str = strconv.FormatBool(b2)</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// Itoa是FormatInt(i, 10) 的简写。</span></span><br><span class="line">	<span class="keyword">var</span> num3 <span class="keyword">int64</span> = <span class="number">9999</span></span><br><span class="line">	str = strconv.Itoa(<span class="keyword">int</span>(num3))</span><br><span class="line">	fmt.Printf(<span class="string">"str type %T str=%q \n"</span>, str, str)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"99"</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"23.4560000000"</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"true"</span></span><br><span class="line">str <span class="keyword">type</span> <span class="keyword">string</span> str=<span class="string">"9999"</span></span><br></pre></td></tr></table></figure>
<h5 id="3-13-3-string类型转基本类型">3.13.3 string类型转基本类型</h5>
<p>使用strconv包的函数</p>
<p>func ParseBool(str string) (value bool, err error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (n uint64, err error)
func ParseFloat(s string, bitSize int) (f float64, err error)</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用strconv包函数，string转基本类型</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> str <span class="keyword">string</span> = <span class="string">"true"</span></span><br><span class="line">	<span class="keyword">var</span> b <span class="keyword">bool</span></span><br><span class="line">	<span class="comment">// 1. strconv.ParseBool(str) 函数会返回两个值(value boolm, err error)</span></span><br><span class="line">	<span class="comment">// 2. 因为这里只想获取到value bool, 不想获取err，所以使用_忽略</span></span><br><span class="line">	b, _ = strconv.ParseBool(str)</span><br><span class="line">	fmt.Printf(<span class="string">"b type %T b=%v \n"</span>, b, b)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">var</span> str2 <span class="keyword">string</span> = <span class="string">"123456789"</span></span><br><span class="line">	<span class="keyword">var</span> n1 <span class="keyword">int64</span></span><br><span class="line">	<span class="keyword">var</span> n2 <span class="keyword">int</span></span><br><span class="line">	n1, _ = strconv.ParseInt(str2, <span class="number">10</span>, <span class="number">64</span>)</span><br><span class="line">	n2 = <span class="keyword">int</span>(n1)</span><br><span class="line">	fmt.Printf(<span class="string">"n1 type %T n1=%v \n"</span>, n1, n1)</span><br><span class="line">	fmt.Printf(<span class="string">"n2 type %T n2=%v \n"</span>, n2, n2)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">var</span> str3 <span class="keyword">string</span> = <span class="string">"123.456"</span></span><br><span class="line">	<span class="keyword">var</span> f1 <span class="keyword">float64</span></span><br><span class="line">	f1, _ = strconv.ParseFloat(str3, <span class="number">64</span>)</span><br><span class="line">	fmt.Printf(<span class="string">"f1 type %T f1=%v"</span>, f1, f1)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ <span class="keyword">go</span> run hello.<span class="keyword">go</span></span><br><span class="line">b <span class="keyword">type</span> <span class="keyword">bool</span> b=<span class="literal">true</span></span><br><span class="line">n1 <span class="keyword">type</span> <span class="keyword">int64</span> n1=<span class="number">123456789</span></span><br><span class="line">n2 <span class="keyword">type</span> <span class="keyword">int</span> n2=<span class="number">123456789</span></span><br><span class="line">f1 <span class="keyword">type</span> <span class="keyword">float64</span> f1=<span class="number">123.456</span></span><br></pre></td></tr></table></figure>
<p>说明，因为返回的是int64或者float64，如希望得到int32, float32等，可以做如下处理</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> num5 <span class="keyword">int32</span></span><br><span class="line">num5 = <span class="keyword">int32</span>(num)</span><br></pre></td></tr></table></figure>
<h5 id="3-13-4-string转基本数据类型的注意事项">3.13.4 string转基本数据类型的注意事项</h5>
<p>​		在将string类型转成基本数据类型时，要确保string类型能够转成有效的数据，比如，可以把“123”转成一个整数，但是不能把“hello”转成一个整数，如果这样做，Golang直接将其转成0，其他类型也是一样的道理，float =&gt;0，bool =&gt; false</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wpay.png" alt="King 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="King 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    King
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zhongxc.cc/58832782.html" title="Go语言核心编程">https://zhongxc.cc/58832782.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Go/" rel="tag"># Go</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/d09c1976.html" rel="next" title="BCMath任意精度数学运算-加减乘除">
                <i class="fa fa-chevron-left"></i> BCMath任意精度数学运算-加减乘除
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/a89fc51f.html" rel="prev" title="Go字符串常用的系统函数">
                Go字符串常用的系统函数 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image" src="/assets/images/avatar.jpg" alt="King">
          
            <p class="site-author-name" itemprop="name">King</p>
            <p class="site-description motion-element" itemprop="description"></p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">61</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">16</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crytostring" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:cqzhongxc@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://gitee.com/ikings" target="_blank" title="gitee">
                  
                    <i class="fa fa-fw fa-git"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.stephen520.cn" target="_blank" title="石鹏">
                  
                    <i class="fa fa-fw fa-scribd"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.tutorialspoint.com/index.htm" target="_blank" title="tutorialspoint">
                  
                    <i class="fa fa-fw fa-tumblr"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://leetcode-cn.com/interview" target="_blank" title="leetcode">
                  
                    <i class="fa fa-fw fa-code"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.geeksforgeeks.org/php-addcslashes-function" target="_blank" title="geeksforgeeks">
                  
                    <i class="fa fa-fw fa-diamond"></i></a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#三-golang-变量"><span class="nav-number">1.</span> <span class="nav-text">三、Golang 变量</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-变量的介绍"><span class="nav-number">1.1.</span> <span class="nav-text">3.1 变量的介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-1-1-变量的概念"><span class="nav-number">1.1.1.</span> <span class="nav-text">3.1.1 变量的概念</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-1-2-变量的使用步骤"><span class="nav-number">1.1.2.</span> <span class="nav-text">3.1.2 变量的使用步骤</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-定义变量"><span class="nav-number">1.2.</span> <span class="nav-text">3.2 定义变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-变量使用注意事项"><span class="nav-number">1.3.</span> <span class="nav-text">3.3 变量使用注意事项</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#golang变量使用的多种方式"><span class="nav-number">1.3.1.</span> <span class="nav-text">Golang变量使用的多种方式</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-变量的声明-初始化和赋值"><span class="nav-number">1.4.</span> <span class="nav-text">3.4 变量的声明，初始化和赋值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5-数据类型的基本介绍"><span class="nav-number">1.5.</span> <span class="nav-text">3.5 数据类型的基本介绍</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-6-整数类型"><span class="nav-number">1.6.</span> <span class="nav-text">3.6 整数类型</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-1-基本介绍"><span class="nav-number">1.6.1.</span> <span class="nav-text">3.6.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-2-整数类型"><span class="nav-number">1.6.2.</span> <span class="nav-text">3.6.2 整数类型</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-3-整型的使用细节"><span class="nav-number">1.6.3.</span> <span class="nav-text">3.6.3 整型的使用细节</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-7-小数类型-浮点型"><span class="nav-number">1.7.</span> <span class="nav-text">3.7 小数类型/浮点型</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-7-1-基本介绍"><span class="nav-number">1.7.1.</span> <span class="nav-text">3.7.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-7-2-小数类型使用"><span class="nav-number">1.7.2.</span> <span class="nav-text">3.7.2 小数类型使用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-7-3-小数类型分类"><span class="nav-number">1.7.3.</span> <span class="nav-text">3.7.3 小数类型分类</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-7-4-浮点型使用细节"><span class="nav-number">1.7.4.</span> <span class="nav-text">3.7.4 浮点型使用细节</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-8-字符类型"><span class="nav-number">1.8.</span> <span class="nav-text">3.8 字符类型</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-8-1-基本介绍"><span class="nav-number">1.8.1.</span> <span class="nav-text">3.8.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-8-2-基本使用"><span class="nav-number">1.8.2.</span> <span class="nav-text">3.8.2 基本使用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-8-3-字符类型使用细节"><span class="nav-number">1.8.3.</span> <span class="nav-text">3.8.3 字符类型使用细节</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-8-4-字符类型本质探讨"><span class="nav-number">1.8.4.</span> <span class="nav-text">3.8.4 字符类型本质探讨</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-9-布尔类型"><span class="nav-number">1.9.</span> <span class="nav-text">3.9 布尔类型</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-9-1-基本介绍"><span class="nav-number">1.9.1.</span> <span class="nav-text">3.9.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-9-2-基本使用"><span class="nav-number">1.9.2.</span> <span class="nav-text">3.9.2 基本使用</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-10-string类型"><span class="nav-number">1.10.</span> <span class="nav-text">3.10 string类型</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-10-1-基本使用"><span class="nav-number">1.10.1.</span> <span class="nav-text">3.10.1 基本使用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-10-2-string使用注意事项和细节"><span class="nav-number">1.10.2.</span> <span class="nav-text">3.10.2 string使用注意事项和细节</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-11-基本数据类型的默认值"><span class="nav-number">1.11.</span> <span class="nav-text">3.11 基本数据类型的默认值</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-11-1-基本介绍"><span class="nav-number">1.11.1.</span> <span class="nav-text">3.11.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-11-2-基本数据类型默认值如下"><span class="nav-number">1.11.2.</span> <span class="nav-text">3.11.2 基本数据类型默认值如下</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-12-基本数据类型的相互转换"><span class="nav-number">1.12.</span> <span class="nav-text">3.12 基本数据类型的相互转换</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-12-1-基本介绍"><span class="nav-number">1.12.1.</span> <span class="nav-text">3.12.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-12-2-基本语法"><span class="nav-number">1.12.2.</span> <span class="nav-text">3.12.2 基本语法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-12-3-基本数据类型相互转换的注意事项"><span class="nav-number">1.12.3.</span> <span class="nav-text">3.12.3 基本数据类型相互转换的注意事项</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-13-基本数据类型和string的转换"><span class="nav-number">1.13.</span> <span class="nav-text">3.13 基本数据类型和string的转换</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-13-1-基本介绍"><span class="nav-number">1.13.1.</span> <span class="nav-text">3.13.1 基本介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-13-2-基本类型转string"><span class="nav-number">1.13.2.</span> <span class="nav-text">3.13.2 基本类型转string</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-13-3-string类型转基本类型"><span class="nav-number">1.13.3.</span> <span class="nav-text">3.13.3 string类型转基本类型</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-13-4-string转基本数据类型的注意事项"><span class="nav-number">1.13.4.</span> <span class="nav-text">3.13.4 string转基本数据类型的注意事项</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2020 &mdash; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-random"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">King</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动</div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">主题 &mdash; <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.2</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  

  






  




	





  








  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('3');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.2"></script>


</body>
</html>
